package com.gem.talkbase.fragment;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.jivesoftware.smack.packet.Presence;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import com.gem.talkbase.R;
import com.gem.talkbase.activity.AddFirendActivity;
import com.gem.talkbase.activity.Friend_infoActivity;
import com.gem.talkbase.activity.MainActivity;
import com.gem.talkbase.adapter.PinyinAdapter;
import com.gem.talkbase.bean.Firend;
import com.gem.talkbase.client.Client;
import com.gem.talkbase.service.JSON_FriendList;
import com.gem.talkbase.widget.AssortView;
import com.gem.talkbase.widget.AssortView.OnTouchAssortListener;
import com.gem.talkbase.widget.TitleView;
import com.gem.talkbase.widget.TitleView.OnRightButtonClickListener;
import com.gem.talkbase.widget.XListView;
import com.gem.talkbase.widget.XListView.IXListViewListener;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.PopupWindow; 
import android.widget.TextView;



/**
 * 功能描述：联系人fragment页面
 * @param <BuddyEntity>
 *	
 */

public class Fragment_contact extends Fragment {
	
	 FinalBitmap fb;
	 SharedPreferences sharedPreferences; 
	String requestPath=Client.Firend_URL;
	private PinyinAdapter adapter;
	private XListView  eListView;
	private AssortView assortView;
	private List<String> names;
	private List<Firend> list;
	private Firend firend;
	private View mParent;
	 static  String unick;
	//显示layout下的fragment布局
	private FragmentActivity mActivity;
	//顶部标题栏
	private TitleView mTitle; 
	private View context;
	private LayoutInflater inflater;
	static  String username;
	private MainActivity mainActivity;
	List<HashMap<String, Object>> data;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
	}


	/**
	 * Create a new instance of DetailsFragment, initialized to show the text at
	 * 'index'.
	 */
//	@Override
//	public void onCreate(Bundle savedInstanceState) {
//		super.onCreate(savedInstanceState);
//		
//			username=getArguments().getString(username);
//		
//	}
	

  
// 
//	public static Fragment_contact newInstance(String username) {
//		Fragment_contact f = new Fragment_contact();
//
//		// Supply index input as an argument.
//		Bundle args = new Bundle();
//		args.putString("username", username);
//		f.setArguments(args);
//        
//		return f;
//	}
//
//	public String getShownIndex() {
//		return getArguments().getString("username");  
//	}
public void fun(String username,final View view){
	AjaxParams params = new AjaxParams(); 
	params.put("username", username);
	FinalHttp fh = new FinalHttp();
	fh.post(requestPath, params, new AjaxCallBack<String>() {
		@Override
		public void onFailure(Throwable t, String strMsg) {   
			System.out.println("加载失败！！！");
			super.onFailure(t, strMsg);
		}

		@Override
		public void onLoading(long count, long current) {
			// TODO Auto-generated method stub
			System.out.println("正在加载！！！");
			super.onLoading(count, current);
		}

		@Override  
		public void onSuccess(String jsonString) {
			super.onSuccess(jsonString);
			System.out.println(jsonString+"00000000000000000000000000000000");
			list =new ArrayList<Firend>();
			//JSONObject jsonObject;	
			JSON_FriendList json_FriendList=new JSON_FriendList();
			list=json_FriendList.fun(jsonString);
		    data = new ArrayList<HashMap<String,Object>>();
			Map<String, String> map =new TreeMap<String, String>();
			for(Firend firend : list){
				HashMap<String, Object> item = new HashMap<String, Object>();
				item.put("unick", firend.getUnick());
				item.put("uimage", firend.getUimage());
				data.add(item);
//				System.out.println(data+"==============================");
				map.put(firend.getUnick(), firend.getUimage());
			}
		
			adapter = new PinyinAdapter(getActivity(),view,data);
		
			eListView.setAdapter(adapter);
			for (int i = 0, length = adapter.getGroupCount(); i < length; i++) {
				eListView.expandGroup(i);
			}
		}
	});
}
void updateView(final View view) {
	new Thread() {
		public void run() {
			SystemClock.sleep(2000);
			fun(username, view);
			handler.sendEmptyMessage(0);
		};
	}.start();
}

@SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
	public void handleMessage(android.os.Message msg) {
	
		eListView.setAdapter(adapter);
		eListView.stopRefresh();
	};
};

	@SuppressWarnings("static-access")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		final View view = inflater.inflate(R.layout.fragment_contact, container,false);
		
		eListView = (XListView)view.findViewById(R.id.elist); 
		assortView = (AssortView)view.findViewById(R.id.assort);
		// 下拉刷新
		eListView.setPullRefreshEnable(true);// 显示下拉刷新
		eListView.setPullLoadEnable(false);// 不显示查看更多
		// 下拉刷新
		eListView.setXListViewListener(new IXListViewListener() {

			@Override
			public void onRefresh() {
				updateView(view);
			}

			@Override
			public void onLoadMore() {
				// do nothing
			}
		}, 256);

//		eListView.setAdapter(adapter);
		
		Bundle bundle= this.getArguments();
		if(bundle!=null){
		username=bundle.getString("use");//得到登录id号
		System.out.println("Fragemnt================>>"+bundle);
		System.out.println(username+"==============>username登录id");
		sharedPreferences = getActivity().getSharedPreferences(Client.SAVE_USER,getActivity().MODE_PRIVATE);
		System.out.println(sharedPreferences.getString("userid", "")+"==============");
		if (username==null) {
			username=sharedPreferences.getString("userid", ""); 
		}
		System.out.println(username+"=======================username");
	
        fun(username, view);
	
		eListView.setOnChildClickListener(new OnChildClickListener() { 
      
         @Override
        public boolean onChildClick(ExpandableListView parent, View v, 
             int groupPosition, int childPosition, long id) { 
        	 
        	  Intent intent = new Intent(getActivity(), Friend_infoActivity.class); 
        	  //设置listView里面的名字，并且传送到好友信息界面
        	 intent.putExtra("u",adapter.getChild(groupPosition, childPosition).toString());//点击谁，就是谁的昵称
        	  //传递登录的用户名
        	  
        	  intent.putExtra("name", username);
        	  
        	//  intent.putExtra("u", adapter.getChildId(groupPosition, childPosition));
        	
        	//  System.out.println( groupPosition+"==================="+name.get(0)+"==="+name.get(1));
			  startActivity(intent);
		    System.out.println(adapter.getChild(groupPosition, childPosition).toString()+"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
			Presence presence = new Presence(Presence.Type.available);
		
            return true; 
         } 
    });
		assortView.setOnTouchAssortListener(new OnTouchAssortListener() {
			
//======================初始化点击26个字母弹出来的字母布局==================================================================
			View layoutView=LayoutInflater.from(view.getContext())
					.inflate(R.layout.alert_dialog_menu_layout, null);
			TextView text =(TextView) layoutView.findViewById(R.id.content);
			PopupWindow popupWindow ;
			
			public void onTouchAssortListener(String str) {
			   int index=adapter.getAssort().getHashList().indexOfKey(str);
			   if(index!=-1)
			   {
					eListView.setSelectedGroup(index);;
			   }
				if(popupWindow!=null){
				text.setText(str);
				}
				else
				{   
		//设置弹出字母图标的大小====================================
				   popupWindow = new PopupWindow(layoutView,120, 120,false);
		//设置弹出的字母图标导航在fragment中间========================================
			       popupWindow.showAtLocation(view,Gravity.CENTER, 0, 0);
				}
				text.setText(str);
			}	
			public void onTouchAssortUP() {
				if(popupWindow!=null)
				popupWindow.dismiss();
				popupWindow=null;
			}
		});
		}
		return view;
	

	}

	

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mParent = getView();
		mActivity = (FragmentActivity) getActivity();
     

		mTitle = (TitleView) mParent.findViewById(R.id.title);
		//设置联系人按钮的文字 
		mTitle.setTitle(R.string.title_search);
//		mTitle.setLeftButton(R.string.help, new OnLeftButtonClickListener() {
//
//			@Override
//			public void onClick(View button) {
//				backHomeFragment();
//			}
//		});
		mTitle.hiddenLeftButton();
		mTitle.setRightButton(R.string.help, new OnRightButtonClickListener() {

			@Override
			public void onClick(View button) {
				Intent intent =new Intent(getActivity(),AddFirendActivity.class);
				startActivity(intent);
			
			}
		});
//		mTitle.setRightButton(R.string.help, new OnRightButtonClickListener() {
//
//			@Override
//			public void onClick(View button) {
////				goHelp();
//			}
//		});
	}
	
	/**
	 *返回到首页
	 */
//	private void backHomeFragment() {
//		getFragmentManager().beginTransaction()
//				.hide(MainActivity.mFragments[1])
//				.show(MainActivity.mFragments[0]).commit();
//		FragmentIndicator.setIndicator(0);
//	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		if (!hidden) {
		}
	}


}
